package priv.yiyuan.example.design.proxy;

import java.util.Date;

/**
 * 订单处理代理类
 * <p>
 * 代理模式-代理主题
 *
 * @author YiYuan
 * @data 2025/9/26
 * @apoNote
 */
public class OrderProcessorProxy implements OrderProcessor {

    private RealOrderProcessor realOrderProcessor;

    public OrderProcessorProxy(OrderApprovalHandler chainStart) {
        this.realOrderProcessor = new RealOrderProcessor(chainStart);
    }

    private boolean preProcess(Order order) {
        System.out.println("\n[订单预处理代理] 前置处理: 对订单ID: " + order.getOrderId() + " 进行数据校验和安全检查, 时间: " + new Date());
        if (order.getAmount() <= 0) {
            System.out.println("[订单预处理代理] 校验失败: 订单金额必须大于0。");
            return false;
        }

        if (order.getOrderId().contains("INVALID")) {
            System.out.println("[订单预处理代理] 安全检查失败: 订单ID包含非法字符。");
            return false;
        }

        System.out.println("[订单预处理代理] 预处理通过。");
        return true;
    }

    private void postProcess(Order order) {
        System.out.println("[订单预处理代理] 后置处理: 订单ID: " + order.getOrderId() + " 处理完毕, 记录日志。");
    }

    @Override
    public void processOrder(Order order) {

        if (this.preProcess(order)) {
            realOrderProcessor.processOrder(order);
            this.postProcess(order);
        }
        else {
            System.out.println("[订单预处理代理] 订单ID: " + order.getOrderId() + " 未通过预处理, 请求被拒绝。");
        }

    }
}
